/*
 * @Author: 脉迈
 * @Date: 2021-09-15 11:38:07
 * @LastEditors: 脉迈
 * @LastEditTime: 2022-01-28 10:10:10
 */
import React, { useState } from "react";
import {
  Layout,
  Button,
  Upload,
  Popconfirm,
  Modal,
  Input,
  message,
  Dropdown,
  Menu,
  Tooltip,
} from "antd";
import html2canvas from "html2canvas";
import styles from "./Layout.module.scss";
import config from "../config/index";
import EditorBox from "components/EditorBox/EditorBox";
// import SidebarBox from 'components/SidebarBox/SidebarBox';
import SettingBox from "components/SettingBox/SettingBox";
import SidebarBox from "components/SidebarBox/SidebarBox";
import {
  pageComponentsState,
  componentActiveIndexState,
} from "store/modules/element";
import { uploadPsdStatus, PsdPercentStatus } from "store/modules/status";
import { SendOutlined } from "@ant-design/icons";
import { useRecoilState } from "recoil";
import { saveTemplate } from "../api/template";
import { saveBlock } from "../api/block";
import { dataURItoBlob } from "../utils/helper";
import { uploadFile } from "../api/common";
export default function LayoutIndex() {
  const { Header, Content } = Layout;
  const [pageTemplateVisiable, setPageTemplateVisiable] = useState(false);
  const [pageBlockVisiable, setPageBlockVisiable] = useState(false);
  const [templateNmae, setTemplateName] = useState("");
  const [blockName, setBlockName] = useState("");
  // eslint-disable-next-line
  const [componentActiveIndex, setComponentActiveIndex] = useRecoilState(
    componentActiveIndexState
  );
  // eslint-disable-next-line
  const [PsdStatus, setuploadPsdStatus] = useRecoilState(uploadPsdStatus);
  // eslint-disable-next-line
  const [PsdPercent, setPsdPercent] = useRecoilState(PsdPercentStatus);
  // eslint-disable-next-line
  const [pageComponentList, setPageComponentList] =
    useRecoilState(pageComponentsState);
  const onDocumentClick = () => {
    setComponentActiveIndex(0);
  };
  /**
   * @description 上传PSD
   */
  const handleUploadChange = (obj: any) => {
    setPsdPercent(obj.file.percent);
    setuploadPsdStatus(true);
    if (obj.file.percent === 100) {
    }
    obj.fileList.forEach((imgItem: any) => {
      if (imgItem && imgItem.status === "done" && imgItem.response) {
        setuploadPsdStatus(false);
        psdTransformPageData(imgItem.response);
      }
    });
  };

  const psdTransformPageData = (psdData: any) => {
    console.log(psdData);
    let { document, elements } = psdData;

    let page: any = {};
    let components: any = [];
    page.width = document.width;
    page.height = document.height;
    for (let i = 0; i < elements.length; i++) {
      if (elements[i].type === "blockImage") {
        components.push({
          name: "blockImage",
          style: {
            position: "absolute",
            width: elements[i].width / 2,
            height: elements[i].height / 2,
            top: elements[i].top / 2,
            left: elements[i].left / 2,
            rotate: 0,
            zIndex: 1,
            display: elements[i].visible,
            opacity: elements[i].opacity,
          },

          properties: {
            src: {
              label: "图片地址",
              value: elements[i].imageSrc,
              format: "image",
              editorType: "Input",
              attr: "src",
            },
            link: {
              label: "跳转链接",
              value: "https://www.baidu.com",
              format: "text",
              editorType: "Input",
              attr: "link",
            },
          },
          properStyle: {},
        });
      } else if (elements[i].type === "blockText") {
        components.push({
          name: "blockText",
          style: {
            position: "absolute",
            width: elements[i].width / 2,
            height: elements[i].height / 2,
            top: elements[i].top / 2,
            left: elements[i].left / 2,
            display: elements[i].visible,
            opacity: elements[i].opacity,
            zIndex: 1,
          },
          properties: {
            text: {
              label: "文本",
              value: elements[i].text.value,
              format: "text",
              editorType: "TextArea",
              attr: "text",
            },
            font: {
              label: "字体样式",
              value: {
                fontWeight: elements[i].text.font.weights[0],
                fontStyle: elements[i].text.font.styles[0],
                textDecoration: "unset",
                textAlign: elements[i].text.font.alignment[0],
                color: `rgba(${elements[i].text.font.colors[0].join(",")})`,
              },
              editorType: "FontType",
              attr: "text",
            },
          },
          properStyle: {
            lineHeight: {
              label: "行高",
              value: "1.8",
              format: "lineHeight",
              editorType: "Input",
              attr: "lineHeight",
            },
            fontSize: {
              label: "字体大小",
              value: elements[i].text.font.sizes[0] / 3,
              format: "fontSize",
              editorType: "InputNumber",
              attr: "fontSize",
            },
            fontFamily: {
              label: "字体",
              value: elements[i].text.font.names.join(","),
              editorType: "Select",
              options: [
                {
                  label: "默认字体",
                  value: "fontA",
                },
                {
                  label: "B字体",
                  value: "fontB",
                },
              ],
              attr: "fontFamily",
            },
          },
        });
      }
    }
    let pageComponentLists = [
      {
        children: components,
        style: {
          backgroundColor: "rgba(255,255,255,1)",
          backgroundImage: "",
          backgroundSize: "cover",
          height: document.height / 2,
          position: "relative",
        },
      },
    ];
    console.log(pageComponentLists);
    localStorage.setItem("data", JSON.stringify(pageComponentLists));
    setPageComponentList(pageComponentLists);
  };
  const handleClearConfirm = () => {
    setPageComponentList([]);
  };
  // 处理保存页面模板
  const handleSavePageTemplate = () => {
    let params = {
      name: templateNmae,
      data: JSON.stringify(pageComponentList),
    };
    // screenshots();
    saveTemplate(params).then((res) => {
      setTemplateName("");
      setPageTemplateVisiable(false);
      message.success("保存成功");
    });
  };

  // 处理保存模块
  const handleSaveBlock = () => {
    let params = {
      name: blockName,
      data: JSON.stringify(pageComponentList),
    };
    saveBlock(params).then((res) => {
      setBlockName("");
      setPageBlockVisiable(false);
      message.success("保存成功");
    });
  };

  const handleClickMenu = (target: any) => {
    if (target.key === "block") {
      setPageTemplateVisiable(true);
    } else {
      setPageBlockVisiable(true);
    }
  };

  /**
   * 提供截屏作为项目主图
   */
  const screenshots = () => {
    const el = document.querySelector("#canvas-panel") as HTMLElement;
    return new Promise((resolve, reject) => {
      html2canvas(el, {
        proxy: `${config.baseURL}/html2canvas/corsproxy`,
      }).then((canvas: any) => {
        const dataUrl = canvas.toDataURL("image/jpeg", 0.6);
        const blob = dataURItoBlob(dataUrl);
        const file = new window.File([blob], +new Date() + ".png", {
          type: "image/png",
        });

        let params: any = new FormData();
        params.append("file", file);
        uploadFile(params)
          .then((res: any) => {
            resolve(res.body);
          })
          .catch((err: any) => {
            reject(err);
          });
      });
    });
  };
  return (
    <div>
      <Layout className="layout">
        <Header className={styles.header}>
          <div>
            <i
              className={`${styles.logo} iconfont icon-tubiaodajianxiliebeifen2`}
            ></i>
            <h1>EASY 搭建平台</h1>
          </div>
          <div className={styles.btns}>
            <div className={styles.item}>预览</div>

            <Tooltip title="psd源文件大小最好不要超过30M，过大会导致浏览器卡顿甚至卡死; 尽可能合并图层，并栅格化所有图层;较复杂的图层样式，如滤镜、图层样式等无法读取">
              <div className={styles.item}>
                <Upload
                  name="file"
                  action={`http://10.10.11.31:8888/psd`}
                  showUploadList={false}
                  onChange={(obj) => {
                    handleUploadChange(obj);
                  }}
                >
                  PSD
                </Upload>
              </div>
            </Tooltip>

            {/* <div className={styles.item}>
              预览
            </div> */}
            <div className={styles.item}>
              <Popconfirm
                placement="bottom"
                title="是否清空画布数据"
                onConfirm={() => {
                  handleClearConfirm();
                }}
                okText="是"
                cancelText="否"
              >
                清空画布
              </Popconfirm>
            </div>

            <Dropdown.Button
              type="primary"
              loading={false}
              overlay={
                <Menu onClick={(target) => handleClickMenu(target)}>
                  <Menu.Item key="block">保存为页面模板</Menu.Item>
                  <Menu.Item key="template">保存为模块</Menu.Item>
                </Menu>
              }
              onClick={() => {
                console.log("2");
              }}
            >
              发布页面
            </Dropdown.Button>
          </div>
        </Header>
        <Content className={styles.content}>
          <div className={styles.left}>
            <SidebarBox></SidebarBox>
          </div>
          <div
            className={styles.center}
            onClick={() => {
              onDocumentClick();
            }}
          >
            <EditorBox></EditorBox>
          </div>
          <div className={styles.right}>
            <SettingBox></SettingBox>
          </div>
        </Content>
      </Layout>
      <Modal
        title="存为模块"
        visible={pageBlockVisiable}
        onOk={handleSaveBlock}
        okText="保存"
        cancelText="取消"
        onCancel={() => {
          setPageBlockVisiable(false);
        }}
      >
        <Input
          placeholder="请输入模块名称"
          onChange={(e) => {
            setBlockName(e.target.value);
          }}
          value={blockName}
        />
      </Modal>
      <Modal
        title="存为页面模板"
        visible={pageTemplateVisiable}
        onOk={handleSavePageTemplate}
        okText="保存"
        cancelText="取消"
        onCancel={() => {
          setPageTemplateVisiable(false);
        }}
      >
        <Input
          placeholder="请输入页面模板名称"
          onChange={(e) => {
            setTemplateName(e.target.value);
          }}
          value={templateNmae}
        />
      </Modal>
    </div>
  );
}
